const crypto = require('crypto');
const config = require('../../config');

class FeishuCrypto {
  constructor() {
    this.encryptKey = config.feishu.encryptKey;
    this.verificationToken = config.feishu.verificationToken;
  }

  /**
   * 验证飞书webhook签名
   * @param {string} timestamp 时间戳
   * @param {string} nonce 随机数
   * @param {string} body 请求体
   * @param {string} signature 签名
   * @returns {boolean} 验证结果
   */
  verifySignature(timestamp, nonce, body, signature) {
    try {
      const stringToSign = timestamp + nonce + this.encryptKey + body;
      const hash = crypto.createHash('sha256');
      hash.update(stringToSign);
      const expectedSignature = hash.digest('hex');
      
      return signature === expectedSignature;
    } catch (error) {
      console.error('验证签名失败:', error);
      return false;
    }
  }

  /**
   * 解密飞书webhook数据
   * @param {string} encryptedData 加密数据
   * @returns {object|null} 解密后的数据
   */
  decryptData(encryptedData) {
    try {
      const key = Buffer.from(this.encryptKey, 'utf8');
      const iv = key.slice(0, 16);
      const encrypted = Buffer.from(encryptedData, 'base64');
      
      const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
      let decrypted = decipher.update(encrypted, null, 'utf8');
      decrypted += decipher.final('utf8');
      
      return JSON.parse(decrypted);
    } catch (error) {
      console.error('解密数据失败:', error);
      return null;
    }
  }

  /**
   * 加密响应数据
   * @param {object} data 要加密的数据
   * @returns {string} 加密后的数据
   */
  encryptData(data) {
    try {
      const key = Buffer.from(this.encryptKey, 'utf8');
      const iv = key.slice(0, 16);
      const jsonString = JSON.stringify(data);
      
      const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
      let encrypted = cipher.update(jsonString, 'utf8', 'base64');
      encrypted += cipher.final('base64');
      
      return encrypted;
    } catch (error) {
      console.error('加密数据失败:', error);
      return null;
    }
  }
}

module.exports = new FeishuCrypto(); 